<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>防抖案例</title>
</head>
<body>
    <input type="text" class="inp">

<script>

    var oInp = document.getElementsByClassName("inp")[0];
    oInp.onkeyup = antiShake(changeInp,1000,true);
    function changeInp(){
        console.log(1);
    }

    function antiShake(fn,time,isNow){
        var t = null,
            res;
        var debounced = function(){
            var _this = this;

            if(t){
                clearTimeout(t);
            }

            if(isNow){  //是否立刻
                var exec = !t; //说明 是第一次执行

                t = setTimeout(function(){
                    t = null;
                },time);

                if(exec){
                    res = fn.apply(_this);
                }
            }else{
                t = setTimeout(function(){
                    res = fn.apply(_this);
                },time);
            }
            return res;
        };
        debounced.remove = function(){
            clearTimeout(t);
            t = null;
        };
        return debounced;
    }
</script>
</body>
</html>
